package cn.ezios.huo.s3;


import cn.ezios.huo.s3.bean.HuoStorageAccessCard;
import cn.ezios.huo.s3.core.HuoS3StorageCore;
import cn.ezios.huo.s3.core.HuoStorageCoreWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * 拼装核心
 */
@Slf4j
@Component
@AllArgsConstructor
public class HuoStorageCombiner implements ApplicationRunner {

    private final Environment environment;

    private final HuoStorageCoreWrapper wrapper;

    /**
     * 切换或者使Core生效
     * @param card
     * @return
     */
    public boolean effectCore(HuoStorageAccessCard card){
        HuoS3StorageCore core = new HuoS3StorageCore(card);
        this.wrapper.setHuoStorageCore(core);
        return true;
    }

    /**
     *   access-key: test
     *   secret-key: test222222
     *   bucket-name: sxln
     *   endpoint: http://127.0.0.1:9000
     *   region: cn-taiyuan
     */
    public void defaultCore(){
        log.info("[{}]初始化默认Core",this.getClass().getSimpleName());
        String bucketName = environment.getProperty("s3.bucket-name");
        String endpoint = environment.getProperty("s3.endpoint");
        String region = environment.getProperty("s3.region");
        String accessKey = environment.getProperty("s3.access-key");
        String secretKey = environment.getProperty("s3.secret-key");
        HuoStorageAccessCard card = HuoStorageAccessCard.builder()
                .accessKey(accessKey)
                .secretKey(secretKey)
                .bucketName(bucketName)
                .endpoint(endpoint)
                .region(region)
                .expireMinutes(Duration.ofMinutes(3))
                .build();
        effectCore(card);
        log.info("[{}]默认Core创建完成",this.getClass().getSimpleName());
        log.info("[{}]测试是否生效",this.getClass().getSimpleName());
        String previewUrl = wrapper.core().getPreviewUrl("a.txt");
        log.info("[{}]点击预览：\n{}",this.getClass().getSimpleName(),previewUrl);
    }


    @Override
    public void run(ApplicationArguments args) throws Exception {
        defaultCore();
    }
}
